package com.hzb.LNReader;

import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;

import com.hzb.LNReader.util.ReaderPref;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class ImageViewerActivity extends Activity {
	private static final String LOG = ImageViewerActivity.class.getSimpleName();
	public static final String DST_IMG = "DST_IMG";
	private Matrix matrix;
	private ImageView imgView;
	private int screenWidth, screenHeight;
	private int rawWidth, rawHeight;

	private float currScale = 1;
	
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (ReaderPref.isFullScreen()) {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
		}
		
		String imgPath = getIntent().getStringExtra(DST_IMG);
		// String imgPath = "/sdcard/ttt.png";
		Bitmap bmp = BitmapFactory.decodeFile(imgPath);
		// Bitmap bmp = BitmapFactory.decodeResource(getResources(),
		// R.drawable.untitled);
		if (bmp == null) {
			finish();
		}
		imgView = new ImageView(this);
		imgView.setImageBitmap(bmp);
		imgView.setScaleType(ScaleType.MATRIX);
		imgView.setHorizontalScrollBarEnabled(true);
		imgView.setVerticalScrollBarEnabled(true);
		rawWidth = currWidth = bmp.getWidth();
		rawHeight = currHeight = bmp.getHeight();
		matrix = new Matrix();
		imgView.setImageMatrix(matrix);
		imgView.setOnTouchListener(new OnTouchListener() {
			private GestureDetector detector = new GestureDetector(
					new ImageViewerGestureListener());

			double d1 = 0;
			float srcScale = 1;
			
			private void onMultiDown(MotionEvent e) {
				Log.i(LOG, "MultiTouch!!!");
				int dx1 = (int) e.getX(0) - (int) e.getX(1);
				int dy1 = (int) e.getY(0) - (int) e.getY(1);
				d1 = dx1 * dx1 + dy1 * dy1;
				srcScale = currScale;
			}
			
			private void onMultiMove(MotionEvent e2) {
				Log.i(LOG, "MultiMove!!!");
				int x = (int) ((e2.getX(0) + e2.getX(1)) / 2);
				int y = (int) ((e2.getY(0) + e2.getY(1)) / 2);
				
				int dx2 = (int) e2.getX(0) - (int) e2.getX(1);
				int dy2 = (int) e2.getY(0) - (int) e2.getY(1);
				
				int d2 = dx2 * dx2 + dy2 * dy2;
				float scale = (float)Math.sqrt(d2 / d1);
				zoom(x, y, srcScale * scale);
			}
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getPointerCount() > 1) {
					if (d1 == 0) {
						onMultiDown(event);
					} else {
						onMultiMove(event);
					}
					return true;
				} else {
					d1 = 0;
					return detector.onTouchEvent(event);
				}
			}
		});
		setContentView(imgView);
		imgView.post(new Runnable() {
			@Override
			public void run() {
				screenHeight = imgView.getHeight();
				screenWidth = imgView.getWidth();
			}
		});
		if (ReaderPref.isScreenNotTimeout()) {
			imgView.setKeepScreenOn(true);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (ReaderPref.oldScreenTimeout > 0
				&& !android.provider.Settings.System.putInt(
						getContentResolver(), SCREEN_OFF_TIMEOUT,
						ReaderPref.oldScreenTimeout)) {
			Log.e(LOG, "Error reseting screen timeout");
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private int currWidth, currHeight;
	private float[] matrixValue = new float[9];

	private void updateCurrSize() {
		matrix.getValues(matrixValue);
		currWidth = (int) (rawWidth * matrixValue[0]);
		currHeight = (int) (rawHeight * matrixValue[0]);
	}

	public void zoom(int x, int y, float scale) {
		matrix.setScale(scale, scale);
		updateCurrSize();
		int ax = imgView.getScrollX() + x;
		int ay = imgView.getScrollY() + y;
		float diffScale = scale / currScale;
		ax = ((int) (ax * diffScale)) - x;
		ay = ((int) (ay * diffScale)) - y;
		imgView.setImageMatrix(matrix);
		
		if (currWidth < screenWidth || ax < 0) {
			ax = 0;
		} else if (ax + screenWidth > currWidth) {
			ax = currWidth - screenWidth;
		}
		
		if (screenHeight > currHeight || ay < 0) {
			ay = 0;
		} else if (ay + screenHeight > currHeight) {
			ay = currHeight - screenHeight;
		}
		
		imgView.scrollTo(ax, ay);
		currScale = scale;
	}

	public void scrollBy(int dx, int dy) {
		int sx = imgView.getScrollX();
		if (screenWidth > currWidth || sx < -dx)
			dx = -sx;
		else if (sx + dx + screenWidth > currWidth)
			dx = currWidth - screenWidth - sx;

		int sy = imgView.getScrollY();
		if (screenHeight > currHeight || sy < -dy)
			dy = -sy;
		else if (sy + dy + screenHeight > currHeight)
			dy = currHeight - screenHeight - sy;

		imgView.scrollBy(dx, dy);
	}

	class ImageViewerGestureListener extends SimpleOnGestureListener {

		public ImageViewerGestureListener() {
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			zoom((int) e.getX(), (int) e.getY(), currScale * 0.75f);
			return true;
		}

		@Override
		public boolean onDoubleTap(MotionEvent e) {
			zoom((int) e.getX(), (int) e.getY(), currScale * 1.25f);
			return true;
		}

		double d1;
		float srcScale;
		
		@Override
		public boolean onDown(MotionEvent e) {
			return true;
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			scrollBy((int) distanceX, (int) distanceY);
			return true;
		}
	}
	

}
